<template>
  <div class="content-detail">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header
          icon="el-icon-arrow-left"
          content="创建新标段"
          @back="goback"
        >
        </el-page-header>
        <div class="card-box--downloadbtn">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </div>
    </el-card>

    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>项目基础信息</span>
          <div v-if="showInfo" @click="showInfo = !showInfo" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="showInfo = !showInfo" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>

      <el-collapse-transition>
        <el-form
          :model="formData"
          class="content-box"
          :rules="rules"
          ref="formDataRef"
          label-width="160px"
          v-show="showInfo"
        >
          <el-form-item label="标段编号" prop="sectionCode">
            <el-input
              v-model.trim="formData.sectionCode"
              class="width-custom200"
            ></el-input>
          </el-form-item>

          <el-form-item label="标段名称" prop="sectionName">
            <el-input
              v-model.trim="formData.sectionName"
              class="width-custom200"
            ></el-input>
          </el-form-item>

          <el-form-item label="项目管理员" prop="leaderInfo">
            <el-select
              v-model="formData.leaderInfo"
              filterable
              clearable
              remote
              placeholder="请输入姓名"
              :remote-method="getUserData"
              value-key="value"
              class="width-custom200"
            >
              <el-option
                id="default-option"
                v-for="item in userList"
                :key="item.value"
                :label="item.label"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="标段合同" prop="contractNum">
            <el-select
              v-model="formData.contractNum"
              value-key="dicCode"
              class="width-custom200"
            >
              <el-option
                class="default-option"
                v-for="item in contractTypeList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item.dicCode"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="设置工程类型" prop="projectTypeModel">
            <div class="m-4">
              <el-cascader
                v-model="formData.projectTypeModel"
                :show-all-levels="false"
                @change="handleChange"
                :options="engineeringList"
                :props="props2"
                ref="cascader"
                collapse-tags
                collapse-tags-tooltip
                clearable
              />
            </div>
          </el-form-item>

          <el-form-item label="工程类型">
            <span
              class="text--info form-detail section"
              v-for="(item, index) in engineerTypeArray"
              :key="index"
              >{{ item }}</span
            >
          </el-form-item>

          <el-form-item label="子工程类型">
            <span
              class="text--info form-detail section"
              v-for="(item, index) in ext1Array"
              :key="index"
              >{{ item }}</span
            >
          </el-form-item>

          <el-form-item label="分部">
            <span
              class="text--info form-detail section"
              v-for="(item, index) in fbTypeArray"
              :key="index"
              >{{ item }}</span
            >
          </el-form-item>

          <el-form-item label="子分部">
            <span
              class="text--info form-detail section"
              v-for="(item, index) in zfbTypeArray"
              :key="index"
              >{{ item }}</span
            >
          </el-form-item>

          <el-form-item label="分项">
            <span
              class="text--info form-detail section"
              v-for="(item, index) in fxTypeArray"
              :key="index"
              >{{ item }}</span
            >
          </el-form-item>
        </el-form>
      </el-collapse-transition>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import { getUserList } from "/@/api/user";
import {
  addSection,
  updateSection,
  getSectionInfo,
  getBaseTree
} from "/@/api/projects";
// import { postDictList } from "/@/api/home";
import { storageLocal } from "/@/utils/storage";
// import { ElMessageBox } from "element-plus";

export default defineComponent({
  setup() {
    const route = useRoute();
    const router = useRouter();
    const formDataRef = ref<HTMLFormElement | null>(null) as any;
    const cascader = ref<HTMLFormElement | null>(null) as any;
    // const {proxy} = getCurrentInstance() as any;
    let projectInfo = storageLocal.getItem("projectInfo");
    let userList = ref([]);
    let contractTypeList = [
      { dicValue: "A类合同", dicCode: "A" },
      { dicValue: "B类合同", dicCode: "B" }
    ];
    let state = reactive({
      formData: {
        sectionCode: "",
        sectionName: "",
        projectId: projectInfo?.id,
        projectName: projectInfo?.name,
        leaderInfo: "" as any,
        leaderName: "",
        leaderId: "",
        contractNum: "" as any,
        secEngineerList: [],
        engineerTypeName: "",
        ext1: "",
        fbTypeName: "",
        zfbTypeName: "",
        fxTypeName: "",
        projectTypeModel: "" as any
      },
      engineerTypeArray: [],
      ext1Array: [],
      fbTypeArray: [],
      zfbTypeArray: [],
      fxTypeArray: [],
      showInfo: true,
      engineeringList: [],
      props2: {
        multiple: true,
        value: "id",
        label: "itemText",
        emitPath: false //只返回改节点的值
      }
    });

    const rules = {
      sectionCode: [
        { required: true, message: "请输入标段编号", trigger: "blur" }
      ],
      sectionName: [
        { required: true, message: "请输入标段名称", trigger: "blur" }
      ],
      leaderInfo: [
        { required: true, message: "请填写项目管理员", trigger: "change" }
      ],
      contractNum: [
        { required: true, message: "请选择标段合同", trigger: "change" }
      ],
      projectTypeModel: [
        { required: true, message: "请设置工程类型", trigger: "change" }
      ]
    };

    // 合同类型
    // const initProjectTypeList = async () => {
    //   try {
    //     const { data } = await postDictList({ dicType: "thd_pro_type" });
    //     contractTypeList.value = data || [];
    //   } catch (err) {
    //     console.log(err);
    //   }
    // };

    //过滤最后一级children为空数组数据
    const getTreeData = data => {
      for (var i = 0; i < data.length; i++) {
        if (data[i]?.children?.length) {
          // children若不为空数组，则继续 递归调用 本方法
          data[i].isLast = false;
          getTreeData(data[i].children);
        } else {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
          data[i].isLast = true; //判断是否最后一级
        }
      }
      return data;
    };

    // 工程类型
    const getProjectBaseList = async () => {
      try {
        const { data } = await getBaseTree({ pageNum: 1, pageSize: 0 });
        state.engineeringList = getTreeData(data) || [];
      } catch (err) {
        console.log(err);
      }
    };

    const handleChange = () => {
      let secEngineerList = [];
      // const obj = proxy.$refs['cascader'].getCheckedNodes() //标签上定义的 ref值
      state.engineerTypeArray = [];
      state.ext1Array = [];
      state.fbTypeArray = [];
      state.zfbTypeArray = [];
      state.fxTypeArray = [];
      const obj = cascader.value.getCheckedNodes();
      const data = obj.filter(item => item?.data?.isLast);
      data.forEach(item => {
        state.engineerTypeArray.push(item.pathLabels[0]);
        state.ext1Array.push(item.pathLabels[1]);
        state.fbTypeArray.push(item.pathLabels[2]);
        state.zfbTypeArray.push(item.pathLabels[3]);
        state.fxTypeArray.push(item.pathLabels[4]);
        if (item?.pathNodes?.length) {
          item.pathNodes.forEach(obj => {
            secEngineerList.push({
              parentId: obj.data.parentId,
              selectId: obj.data.id,
              selectName: obj.data.itemText,
              selectType: obj.data.itemType
            });
          });
        }
      });
      state.engineerTypeArray = unique(state.engineerTypeArray);
      state.ext1Array = unique(state.ext1Array);
      state.fbTypeArray = unique(state.fbTypeArray);
      state.zfbTypeArray = unique(state.zfbTypeArray);
      state.fxTypeArray = unique(state.fxTypeArray);
      let secEngineerListArray = uniqueObject(secEngineerList, "selectId");
      state.formData.secEngineerList = secEngineerListArray;
    };

    const unique = arr => {
      return Array.from(new Set(arr));
    };

    const uniqueObject = (arr, key) => {
      let set = [];
      let result = [];
      for (let val of arr) {
        if (!set.includes(val[key])) {
          result.push(val);
          set.push(val[key]);
        }
      }
      return result;
    };

    //获取项目组成员
    const getUserData = async (query = "") => {
      if (!query) {
        userList.value = [];
        return;
      }
      try {
        const params = {
          pageNum: 1,
          pageSize: 100,
          nameLike: query
        };
        const { code, data } = await getUserList(params);
        if (code === 200) {
          userList.value = data.list.map(item => {
            return { value: item.id, label: `${item.name}(${item.userName})` };
          });
        }
      } catch (err) {
        console.log(err);
      }
    };

    // 获取标段详情
    const getSectionDetail = async () => {
      try {
        const { code, data } = await getSectionInfo({ id: sectionId });
        if (code === 200) {
          state.formData = data || [];
          state.engineerTypeArray = data?.engineerTypeName.split(",");
          state.ext1Array = data?.ext1.split(",");
          state.fbTypeArray = data?.fbTypeName.split(",");
          state.zfbTypeArray = data?.zfbTypeName.split(",");
          state.fxTypeArray = data?.fxTypeName.split(",");
          state.formData.leaderInfo = {
            value: +data?.leaderId,
            label: data?.leaderName
          };
          userList.value = [state.formData.leaderInfo];
          const projectTypeModel = data.secEngineerList.filter(item => {
            return item.selectType === "D";
          });
          state.formData.projectTypeModel = projectTypeModel.map(item => {
            return item.selectId;
          });
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleSave = async () => {
      try {
        const isValid = await new Promise(resolve =>
          formDataRef.value.validate(resolve)
        );
        if (!isValid) return;
        state.formData.engineerTypeName = state.engineerTypeArray.join();
        state.formData.ext1 = state.ext1Array.join();
        state.formData.fbTypeName = state.fbTypeArray.join();
        state.formData.zfbTypeName = state.zfbTypeArray.join();
        state.formData.fxTypeName = state.fxTypeArray.join();
        state.formData.leaderId = state.formData.leaderInfo.value;
        state.formData.leaderName = state.formData.leaderInfo.label;
        storageLocal.getItem("projectInfo");
        storageLocal.setItem("sectionAdminInfo", {
          id: state.formData.leaderId,
          name: state.formData.leaderName
        });
        if (sectionId) {
          handleUpdate();
        } else {
          handleAdd();
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleAdd = async () => {
      const { code, message } = await addSection(state.formData);
      if (code === 200) {
        NotifMessage.success(message);
        goback();
      } else {
        if (!message) return;
        NotifMessage.error(message);
      }
    };

    const handleUpdate = async () => {
      let params = Object.assign({}, state.formData, { id: sectionId });
      const { code, message } = await updateSection(params);
      if (code === 200) {
        NotifMessage.success(message);
        goback();
      } else {
        if (!message) return;
        NotifMessage.error(message);
      }
    };

    const goback = () => {
      router.push("/projectsA/proManage/section");
    };

    // initProjectTypeList();
    getProjectBaseList();
    const sectionId = route?.query?.id;
    if (sectionId) {
      getSectionDetail();
    }

    return {
      ...toRefs(state),
      formDataRef,
      userList,
      contractTypeList,
      rules,
      route,
      goback,
      getUserData,
      handleSave,
      handleChange,
      cascader
    };
  }
});
</script>
<style lang="scss" scoped>
.section {
  min-width: auto !important;
  margin-right: 8px;
  margin-bottom: 8px;
}
</style>
